#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <functional>
#include "Tcpserver.hpp"
#include "HttpPortocol.hpp"
using namespace TcpServerModule;
using func_pre_t = std::function<void(HttpRequest &, HttpResponse &)>;

class Httpserver
{

public:
    Httpserver(int port) : _server(std::make_unique<TcpServer>(port))
    {
    }
    void Resgiter(std::string path, func_pre_t func)
    {
        _pre_handle_funcs[path]=func;
    }
    bool SafeCheck(std::string &service)
    {
        auto iter=_pre_handle_funcs.find(service);//查找是否有注册的服务
        return iter!=_pre_handle_funcs.end();//如果找到了就返回true，否则返回false
    }
    void start()
    {
        _server->InitServer([this](SockPtr sockfd, InetAddr client)
                            { return this->HandlerRequest(sockfd, client); });
        _server->Loop();
    }
    bool HandlerRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HandlerRequest, client ip is " << sockfd->fd() << "and port is " << client.Addr();
        std::string request;
        sockfd->Recv(&request);
        std::cout << request; // 字节流的请求
        HttpRequest req;
        req.Deserialize(request);
        // req.Print();
        HttpResponse resp;
        resp.Bulid(req);
        //请求应该分为两类:1 请求一般的静态资源 2 提交参数 携带参数 需要我们进行交互设置
        if(req.ItIsExec())
        {
            // 处理参数
            std::string service=req.Path();
            if(SafeCheck(service))
                _pre_handle_funcs[req.Path()](req,resp);
            else
                resp.Bulid(req);
        }
        else
        {
            resp.Bulid(req);
        }
        std::string response;
        resp.Serialize(&response);
        sockfd->Send(response);
        // std::cout << "request is " <<std::endl;
        //  std::cout<<request << std::endl;

        //         std::string retsned = "HTTP/1.1 200 OK\r\n\r\n";
        //         std::string content = "<!DOCTYPE html>\
//                             <html >\
//                         <head>\
//                     <meta charset=\"UTF-8\">\
//     <title>欢迎页面</title>\
// </head>\
// <body>\
//     <h1>欢迎来到我们的网站！</h1>\
//     <p>我们很高兴你来到这里。请尽情探索我们的内容。</p>\
//     <a>点击这里开始</a>\
// </body>\
// </html>";
        //         std::string httphands=retsned+content;
        //         sockfd->Send(httphands);

        return true;
    }
    ~Httpserver()
    {
    }

private:
    std::unique_ptr<TcpServer> _server;
    std::unordered_map<std::string,func_pre_t> _pre_handle_funcs;
};